package io.github.iogogogo.scheduled.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import io.github.iogogogo.commons.exception.BizException;
import io.github.iogogogo.commons.http.OkHttpUtils;
import io.github.iogogogo.commons.util.JsonParse;
import io.github.iogogogo.scheduled.properties.XxlJobProperties;
import io.github.iogogogo.scheduled.service.JobLoginService;
import io.github.iogogogo.scheduled.support.XxlJobHttpConfig;
import io.vavr.Tuple3;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Cookie;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by tao.zeng on 2024/11/19.
 */
@Slf4j
@Component
public class JobLoginServiceImpl implements JobLoginService, InitializingBean {

    @Resource
    private XxlJobProperties xxlJobProperties;

    private XxlJobProperties.AdminProperties admin;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.admin = xxlJobProperties.getAdmin();
    }

    @Override
    public void login() {
        String url = String.join("/", admin.getAddresses(), "login");
        log.debug("xxl-job admin login url: {}", url);

        Map<String, Object> param = new HashMap<>();
        param.put("userName", admin.getUsername());
        param.put("password", admin.getPassword());
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance().setOkHttpClient(XxlJobHttpConfig.getInstance().getOkHttpClient());

        Tuple3<Integer, Boolean, String> tuple3 = okHttpUtils.postForm(url, param);
        String respJson = tuple3._3;

        Map<String, Object> map = JsonParse.tryParse(respJson, new TypeReference<>() {
        });
        if (MapUtils.isNotEmpty(map) && StringUtils.equals(map.get("code").toString(), "200")) {
            log.debug("xxl-job login succeed");
        } else {
            throw new BizException("xxl-job login failure: " + respJson);
        }
    }

    @Override
    public String getCookie() {
        for (int i = 0; i < 3; i++) {
            Cookie cookie = XxlJobHttpConfig.LOGIN_COOKIE.get(XxlJobHttpConfig.COOKIE_KEY);
            if (cookie != null) return String.join("=", cookie.name(), cookie.value());
            login();
        }
        throw new BizException("get xxl-job cookie error!");
    }
}
